package www.lagou.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import www.lagou.entity.Account;
import www.lagou.utils.DateUtils;
import www.lagou.utils.DruidUtil;

import java.sql.SQLException;

public class AccountDao {


    public Account findAccountBycard(String card) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

        String sql = "select * from account  where card = ?";

        Account account = qr.query(sql, new BeanHandler<Account>(Account.class), card);
        double balance = account.getBalance();
        if (account!=null){
            return account;
        }
        return null;
    }

    public void updateAccountBycard(Account account1,Account account2) {
        try {

            //1.获取 QueryRunner对象 自动创建模式
            QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

            //2.编写SQL
            String sql = "update  account set balance  =? where card =?";

            //更新账户1的数据  余额-5000
            int update1 = qr.update(sql, account1.getBalance(), account1.getCard());
            //更账户2的数据  余额+5000
            int update2 = qr.update(sql, account2.getBalance(), account2.getCard());

            //增加转账记录
            insertTransaction(account1,account2);

        } catch (SQLException e) {
            //出错 回滚事务
            e.printStackTrace();
        }




    }

    private void insertTransaction(Account account1,Account account2)  {
        try {

            //1.获取 QueryRunner对象 自动创建模式
            QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
            //2.编写SQL
            String sql = "insert into TRANSACTION (cardid ,tratype,tramoney ,tradate )value(?,?,?,?)";

            int i1 = qr.update(sql,account1.getCard(), "转出", "5000", DateUtils.getDateFormart());
            int i2 = qr.update(sql,account2.getCard(), "转入", "5000", DateUtils.getDateFormart());
        } catch (SQLException e) {
            e.printStackTrace();
        }



    }
}
